﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.OracleClient;

namespace IBS
{
    public partial class IbsDataContext
    {   
        public IEnumerable<SaleOrderList> GetSaleOrders(IMPORTTYPE type)
        {
            string sql = String.Empty;

            if (type == IMPORTTYPE.RPO)
                sql = String.Format(@"SELECT ID_RECORD as INVOICE_ID FROM  edex.WH_SALESORDER WHERE STATUS = 0 AND COMPANY_KEY>5000");
            else
                if (type == IMPORTTYPE.IbsImport)
                    sql = String.Format(@"SELECT ID_RECORD as INVOICE_ID FROM  edex.WH_SALESORDER WHERE STATUS = 0 AND COMPANY_KEY<=5000");


            return new DB
                .Oracle(this.connectionString)
                .Excecute<SaleOrderList>(sql).AsEnumerable();
        }

        public IEnumerable<RPO_DATA> GetRPO(long InvoiceID)
        {
            var sql = String.Format(@"SELECT
                                        LOCATION_KEY,
                                        S.COMPANY COMPANY,
                                        SO.ID_RECORD as InvoiceCode,
                                        '' AS OrderCode,
                                        (SELECT HQC_SHORTCODE FROM EDEX.TBHQCSUPPLIERCODE WHERE SITEID =LOCATION_KEY AND HQC_LONGCODE=COMPANY_KEY) AS SupplierCode,
                                        '1' AS StockLocationCode,
                                        DOC_DATE InvoiceDate,
                                        '1' AS InvoiceType,
                                        LINECOUNT as LinesNumber,
                                        TRIM(to_char(CAST(TOTAL_AMOUNT as NUMBER (8,2)),'99999999999.99')) TotalQTY,
                                        TRIM(to_char(SOL.QUANTITY,'99999999999.99')) AS InvoiceQuantity,
                                        TRIM(to_char(SOL.QUANTITY,'99999999999.99')) AS SupplyQuantity,
                                        '1' AS UOM,
                                        '1.00' AS UOMFactor,
                                        '' AS EmployeeCode,
                                        '.00' AS LineDiscount,
                                        '.00' AS InvoiceDiscount,
                                        '.00' AS InvoiceExtra,
                                        SOL.ACTUAL_PRICE as Cost,
                                        SO.NOTE as Notes,
                                        '' AS TemplateId,
                                        '' AS ItemName,
                                        '' AS OrderNumber,
                                        '' AS Remarks,
                                        SO.ID_RECORD as ExtendedInvoiceNumber,
                                        S.IP  
                                     FROM edex.WH_SALESORDER SO
                                     LEFT JOIN edex.WH_SALESORDERLINES SOL
                                     ON SO.ID_RECORD = SOL.ID_INVOICE
                                     LEFT JOIN HQCDBO.HQC_IMPORT_SITE HQC_SITE
                                     ON SO.LOCATION_KEY = HQC_SITE.HQC_SITE_ID
                                     LEFT JOIN IBSDBO.TBSITE S
                                     ON HQC_SITE.IBS_SITEIBSCODE = S.SITEIBSCODE
                             WHERE  SO.ID_RECORD = {0} ", InvoiceID);

            var data = new DB
                .Oracle(this.connectionString)
                .Excecute<RPO_DATA>(sql);

            return data.AsEnumerable();
        }
        /// <summary>
        /// обновление статуса на "Отправлен"
        /// </summary>
        /// <param name="InvoiceID"></param>
        public void UpdateStatus(long InvoiceID)
        {
            //обновление статуса документа - "ОТПРАВЛЕН НА СТАНЦИЮ"
            var sql = String.Format(@"UPDATE edex.WH_SALESORDER SET STATUS = 1 WHERE ID_RECORD ={0}", InvoiceID);
            new DB
               .Oracle(this.connectionString)
               .Excecute(sql);
        }
    }


    public class HQCSUPPLIER_CODE
    {
        public Int64 SITECODE { get; set; }
        public Int32 HQC_SHORTCODE { get; set; }
        public Int64 HQC_LONGCODE { get; set; }
    }


    public class SaleOrderList
    {
        public Int64 INVOICE_ID { get; set; }
    }

    public class RPO_DATA : StringEditor
    {
        public Int64 LOCATION_KEY { get; set; } //дополнительно поле, для выгузки не используется
        public Int32 COMPANY { get; set; } //дополнительно поле, для выгузки не используется
        public String IP { get; set; }
        public Int64 INVOICECODE { get; set; }
        public String ORDERCODE { get; set; }
        public Int32 SUPPLIERCODE { get; set; }
        public Int32 STOCKLOCATIONCODE { get; set; }
        public DateTime INVOICEDATE { get; set; }
        public String INVOICETYPE { get; set; }
        public Int32 LINESNUMBER { get; set; }
        public String TOTALQTY { get; set; }
        public Int64 ITEMCODE { get; set; }
        public String INVOICEQUANTITY { get; set; }
        public String SUPPLYQUANTITY { get; set; }
        public String UOM { get; set; }
        public String UOMFACTOR { get; set; }
        public String EMPLOYEECODE { get; set; }
        public String LINEDISCOUNT { get; set; }
        public String INVOICEDISCOUNT { get; set; }
        public String INVOICEEXTRA { get; set; }
        public Double COST { get; set; }
        public String NOTES { get; set; }
        public String ITEMPLATEID { get; set; }
        public String ITEMNAME { get; set; }
        public String ORDERNUMBER { get; set; }
        public String REMARKS { get; set; }
        public String EXTENDEDINVOICENUMBER { get; set; }


        public void SerializeToFile(string filePath)
        {
            String spaceCHR = " ";
            String separator = ",";
            StringBuilder resultString = new StringBuilder();
            resultString.Append(String.Concat(GetFormattedString(INVOICECODE.ToString(), 8, spaceCHR, false), separator));//1
            resultString.Append(String.Concat(GetFormattedString(ORDERCODE, 8, spaceCHR, false), separator));//2
            resultString.Append(String.Concat(GetFormattedString(SUPPLIERCODE.ToString(), 8, spaceCHR, false), separator));//3
            resultString.Append(String.Concat(GetFormattedString(STOCKLOCATIONCODE.ToString(), 8, spaceCHR, false), separator));//4
            resultString.Append(String.Concat(GetFormattedString(INVOICEDATE.ToString("dd.MM.yyyy"), 10, spaceCHR, false), separator));//5
            resultString.Append(String.Concat(GetFormattedString(INVOICETYPE, 2, spaceCHR, false), separator));//6
            resultString.Append(String.Concat(GetFormattedString(LINESNUMBER.ToString(), 8, spaceCHR, false), separator));//7
            resultString.Append(String.Concat(GetFormattedString(TOTALQTY.ToString(), 11, spaceCHR, false), separator));//8
            resultString.Append(String.Concat(GetFormattedString(ITEMCODE.ToString(), 13, spaceCHR, true), separator));//9
            resultString.Append(String.Concat(GetFormattedString(INVOICEQUANTITY.ToString(), 11, spaceCHR, false), separator));//10
            resultString.Append(String.Concat(GetFormattedString(SUPPLYQUANTITY.ToString(), 11, spaceCHR, false), separator));//11
            resultString.Append(String.Concat(GetFormattedString(UOM, 8, spaceCHR, false), separator));//12
            resultString.Append(String.Concat(GetFormattedString(UOMFACTOR, 11, spaceCHR, false), separator));//13
            resultString.Append(String.Concat(GetFormattedString(EMPLOYEECODE, 8, spaceCHR, false), separator));//14
            resultString.Append(String.Concat(GetFormattedString(LINEDISCOUNT, 11, spaceCHR, false), separator));//15
            resultString.Append(String.Concat(GetFormattedString(INVOICEDISCOUNT, 11, spaceCHR, false), separator));//16
            resultString.Append(String.Concat(GetFormattedString(INVOICEEXTRA, 11, spaceCHR, false), separator));//17
            resultString.Append(String.Concat(GetFormattedString(COST.ToString(), 11, spaceCHR, false), separator));//18
            resultString.Append(String.Concat(GetFormattedString(NOTES, 50, spaceCHR, false), separator));//19
            resultString.Append(String.Concat(GetFormattedString(ITEMPLATEID, 8, spaceCHR, false), separator));//20
            resultString.Append(String.Concat(GetFormattedString(ITEMNAME, 20, spaceCHR, false), separator));//21
            resultString.Append(String.Concat(GetFormattedString(ORDERNUMBER, 15, spaceCHR, false), separator));//22
            resultString.Append(String.Concat(GetFormattedString(REMARKS, 40, spaceCHR, false), separator));//23
            resultString.Append(GetFormattedString(EXTENDEDINVOICENUMBER, 20, spaceCHR, true));//24
            File.AppendAllText(filePath, resultString.ToString() + "\r\n");
        }
    }

    public class StringEditor
    {
        public virtual string GetFormattedString(string str, byte lenght, string separator, bool leftAlign)
        {
            if (leftAlign)
            {
                if (String.IsNullOrEmpty(str))
                    return "".PadRight(lenght, Convert.ToChar(separator));
                if (str.Length == lenght)
                    return str;
                if (str.Length > lenght)
                    return str.Remove(lenght);
                if (str.Length < lenght)
                    return str.PadRight(lenght, Convert.ToChar(separator));
            }
            else
            {
                if (String.IsNullOrEmpty(str))
                    return "".PadLeft(lenght, Convert.ToChar(separator));
                if (str.Length == lenght)
                    return str;
                if (str.Length > lenght)
                    return str.Remove(lenght);
                if (str.Length < lenght)
                    return str.PadLeft(lenght, Convert.ToChar(separator));
            }
            return null;
        }
    }
}